package com.whatisjee.ssf.domain.dao.impl;

import static org.apache.commons.lang.StringUtils.isNotEmpty;

import com.whatisjee.ssf.misc.Page;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public abstract class AbstractDaoImpl {
        @PersistenceContext(unitName = "ssjee7PU")
        protected EntityManager em;
	
	protected Query createPagedQuery(Page p,
			StringBuilder sb) {
		return createPagedQuery(p, sb, null);
	}

	protected Query createPagedQuery(Page p,
			StringBuilder sb, String alias) {
		return createPagedQuery(p, sb, alias, false);
	}
	
	protected Query createPagedNativeQuery(Page p,
			StringBuilder sb) {
		return createPagedNativeQuery(p, sb, null);
	}

	protected Query createPagedNativeQuery(Page p,
			StringBuilder sb, String alias) {
		return createPagedQuery(p, sb, alias, true);
	}

	private Query createPagedQuery(Page p,
			StringBuilder sb, String alias, boolean isNative) {
		String sortColumn = p.getOrderBy();
		if (isNotEmpty(sortColumn)) {
			sb.append(" ORDER BY ");
			if (isNotEmpty(alias)) {
				sb.append(alias);
				sb.append(".");
			}
			sb.append(sortColumn);
			if (p.getOrder() != null) {
				sb.append(" ");
				sb.append(p.getOrder());
			}
		}

		String sql = sb.toString();
		  
		Query q = null;
		if(isNative){					
			q = em.createNativeQuery(sql);
		}else{
			q = em.createQuery(sql);
		}
				
		q.setFirstResult(p.getFirstRow());
		q.setMaxResults(p.getRows());

		return q;
	}
}